const jwt = require('jsonwebtoken');
const AdminModel = require('../models/adminModel');

const adminAuthMiddleware = async (req, res, next) => {
    try {
        const token = req.headers.authorization?.split(' ')[1];
        
        if (!token) {
            return res.status(401).json({ 
                code: 401,
                message: '请先登录' 
            });
        }

        const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
        
        // 验证是否为管理员
        const admin = await AdminModel.findByUsername(decoded.username);
        if (!admin) {
            return res.status(403).json({ 
                code: 403,
                message: '没有管理员权限' 
            });
        }

        req.admin = admin;
        next();
    } catch (error) {
        if (error.name === 'TokenExpiredError') {
            return res.status(401).json({ 
                code: 401,
                message: '登录已过期，请重新登录' 
            });
        }
        res.status(401).json({ 
            code: 401,
            message: '无效的认证令牌' 
        });
    }
};

module.exports = adminAuthMiddleware; 